package com.zhugang.week02;

/**
 * @program algorithms
 * @description: oddEventList
 * @author: chanzhugang
 * @create: 2022/05/30 21:51
 */
public class OddEventList {

    /**
     * 328. 奇偶链表
     *
     * @param head
     * @return
     */
    public ListNode oddEventList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        // 定义奇链表头节点head，尾节点o = head， 偶链表头节点p = head.next, 尾节点 e = p;
        ListNode o = head;
        ListNode p = head.next;
        ListNode e = p;
        while (o.next != null && e.next != null) {
            o.next = e.next;
            o = o.next;
            e.next = o.next;
            e = e.next;
        }
        o.next = p;
        return head;
    }


    public ListNode oddEventList2(ListNode head) {
        // 分别开辟新的奇偶链表，遍历head，count % 2判断奇偶，尾部插入节点，最后奇链表.next = 偶链表
        ListNode oddHead = new ListNode();
        ListNode oddTail = oddHead;
        ListNode eventHead = new ListNode();
        ListNode eventTail = eventHead;
        ListNode p = head;
        int count = 1;
        while (p != null) {
            ListNode temp = p.next;
            if (count % 2 == 1) {
                p.next = null;
                oddTail.next = p;
                oddTail = p;
            } else {
                p.next = null;
                eventTail.next = p;
                eventTail = p;
            }
            p = temp;
            count++;
        }
        oddTail.next = eventHead.next;
        return oddHead.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}